package com.xyzwps.paimon.furina.common.value

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.*
import com.fasterxml.jackson.databind.module.SimpleModule
import java.util.regex.Pattern


interface StringValue {
    val value: String
}

fun <T : StringValue> SimpleModule.registerStr(clazz: Class<T>, creator: (String) -> T) {
    val serializer = object : JsonSerializer<T>() {
        override fun serialize(v: T?, gen: JsonGenerator, serializers: SerializerProvider) {
            if (v == null) {
                gen.writeNull()
            } else {
                gen.writeString(v.value)
            }
        }
    }

    val deserializer = object : JsonDeserializer<T>() {
        override fun deserialize(p: JsonParser, ctxt: DeserializationContext): T = creator(p.text)
    }

    val keyDeserializer = object : KeyDeserializer() {
        override fun deserializeKey(key: String, ctxt: DeserializationContext): Any = creator(key)
    }

    this.addSerializer(clazz, serializer)
    this.addDeserializer(clazz, deserializer)
    this.addKeySerializer(clazz, serializer)
    this.addKeyDeserializer(clazz, keyDeserializer)
}

val PHONE_PATTERN: Pattern = Pattern.compile("^1[1-9][0-9]{9}$")
val VCODE_PATTERN: Pattern = Pattern.compile("^[0-9]{6}$")